package com.wtwd.campus.h5_manager.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.h5_manager.common.Constant;
import com.wtwd.campus.h5_manager.common.PageDataVO;
import com.wtwd.campus.h5_manager.common.RespCode;
import com.wtwd.campus.h5_manager.common.RespEntity;
import com.wtwd.campus.h5_manager.entity.H5ManageRole;
import com.wtwd.campus.h5_manager.entity.H5ManageUser;
import com.wtwd.campus.h5_manager.entity.vo.H5RolePermissionVo;
import com.wtwd.campus.h5_manager.entity.vo.UpdateRolePermissionVo;
import com.wtwd.campus.h5_manager.service.H5ManageRoleService;
import com.wtwd.campus.h5_manager.service.H5ManagerUserService;
import com.wtwd.campus.utils.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 * <p>
 * 查看角色列表,根据客户来,账号所见角色为自己组织下的角色
 * 只能为自己锁建立角色授权
 *
 * @author mjy
 * @since 2022-03-04
 */
@Api(tags = "h5平台角色管理")
@RestController
@RequestMapping("/webH5-manage-role")
public class H5ManageRoleController {

    private static final Logger logger = LoggerFactory.getLogger(H5ManageRoleController.class);


    @Autowired
    private H5ManageRoleService roleService;


    @Autowired
    private H5ManagerUserService userService;

    @ApiOperation(value = "查询角色列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
    })
    @GetMapping("/queryRolePage")
    public RespEntity<PageDataVO<H5ManageRole>> queryRolePage(@RequestParam(defaultValue = "1") Integer currentPage,
                                                              @RequestParam(defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = userService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("queryRolePage currentPage={},pageSize={}", currentPage, pageSize);
        H5ManageUser user = userService.getUserById(userId);
        if (user == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        Page<H5ManageRole> page = new Page<>(currentPage, pageSize);
        IPage<H5ManageRole> roleIPage = roleService.queryRoleByCustomerIdPage(user.getCustomerId(), page);
        return RespEntity.success(roleIPage);
    }

    /**
     * 新增角色,新增的角色，属于创建人的组织下
     * 角色名称可以重复，在此不鉴别
     */
    @ApiOperation("新增角色")
    @PostMapping("/addRole")
    public RespEntity addRole(@RequestBody H5ManageRole manageRoleVo, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = userService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("addRole userId={}, manageRoleVo={}", userId, manageRoleVo);
        H5ManageUser user = userService.getUserById(userId);
        if (user == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        manageRoleVo.seth5Customer(user.getCustomerId());
        Integer rest = roleService.addRole(manageRoleVo);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);

    }


    /**
     * 获取角色权限列表
     *
     * @param roleId
     * @return
     */
    @ApiOperation("获取角色权限列表")
    @DynamicParameters(name = "getRolePermissionList", properties = {
            @DynamicParameter(name = "roleId", value = "角色id", dataTypeClass = Long.class, required = true)
    })
    @GetMapping("/getRolePermissionList/{roleId}")
    public RespEntity getRolePermissionList(@PathVariable Long roleId, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = userService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("getRolePermissionList roleId={},userId={}", roleId, userId);
        H5ManageUser user = userService.getUserById(userId);
        if (user == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        List<H5RolePermissionVo> h5RolePermissionVos = roleService.getRolePermission(user.getRoleId(), roleId);
        //过滤掉客户管理以及客户管理下面的权限控制(过滤掉菜单id为6,父级菜单id为6的数据)
//        List<H5RolePermissionVo> collect = h5RolePermissionVos.stream().filter(e -> (e.getId() != 6) && (e.getPid() != 6)).collect(Collectors.toList());
        return new RespEntity(RespCode.SUCCESS, TreeUtil.createTree(h5RolePermissionVos));
    }

    /**
     * 授权
     *
     * @param data
     * @param request
     * @return
     */
    @ApiOperation(value = "修改角色权限列表")
    @PutMapping("/updateRolePermission")
    public RespEntity updateRolePermission(@RequestBody UpdateRolePermissionVo data, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = userService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("updateRolePermission data={},userId={}", data.toString(), userId);
        Integer rest = roleService.addRolePermission(data.getRoleId(), data.getPerIds());
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @return
     */
    @ApiOperation("删除角色")
    @DynamicParameters(name = "deleteRole", properties = {
            @DynamicParameter(name = "roleId", value = "角色id", dataTypeClass = Long.class, required = true)
    })
    @DeleteMapping("/deleteRole/{roleId}")
    public RespEntity deleteRole(@PathVariable Integer roleId, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = userService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("getRolePermissionList roleId={},userId={}", roleId, userId);
        Integer rest = roleService.deleteByRoleId(roleId);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }


}

